package com.powernode.controller;

import com.github.pagehelper.PageInfo;
import com.powernode.common.Result;
import com.powernode.domain.User;
import com.powernode.dto.UserDto;
import com.powernode.service.impl.UserService;
import com.powernode.utils.WebMVCUtils;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

//控制登录的类
@Controller
@RequestMapping("/login")
@Api(tags = "控制登录的接口")
public class LoginController {
    @Autowired
    UserService userService;

    @RequestMapping("/doLogin.do")
    @ResponseBody
    public Result denlu(String username, String password, String captcha, HttpSession session) {
        System.out.println(username+"---"+password+"----"+captcha);
        Result result = new Result();
        //取出session中存放的验证码
        Object code = session.getAttribute("code");
        if (!(code + "").equals(captcha)) {
            result.setCode(-1);
            result.setMsg("验证码错误");
            return  result;
        }
        User user = userService.findUser(username, password);
        System.out.println(user);
        if (user == null) {
            result.setMsg("添加数据失败");
            result.setCode(-1);
            return result;
        } else {
            result.setCode(200);
            //登录时校验成功后sassion中存user对象
            //先把密码职位空字符串
              user.setPassword("");
            session.setAttribute("user", user);
            return result;
        }
    }

    /**
     * 退出登录
     *
     * @return
     */
    @RequestMapping("logout.do")
    @ResponseBody
    public Result logout() {
        try {
            //清空session
            WebMVCUtils.getSession().invalidate();
            return new Result(200, "退出成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(-1, "退出登录失败");
        }


    }


}
